<template>
  <div style="width: 80%;">
    <div style="margin-bottom: 30px;margin-left: 30px"><h2>编辑管理员</h2></div>
    <el-form :inline="true" :model="form" :rules="rules" ref="ruleForm" label-width="100px" style="margin-left: 110px;"
             size="max">

      <el-form-item label="用户名" prop="username">
        <el-input prefix-icon="el-icon-user" v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input prefix-icon="el-icon-phone-outline" v-model="form.phone" placeholder="请输入联系方式"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input prefix-icon="el-icon-postcard" v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
    </el-form>

    <div style="text-align: center;margin-top: 20px">
      <el-button type="primary" @click="save" size="medium">提交</el-button>
    </div>
  </div>
</template>
<script>
import request from "@/utils/request";

export default {
  name: "EditAdmin",
  data() {
    const checkPhone = (rule, value, callback) => {   //校验联系方式规则
      if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(value)) {
        callback(new Error('请输入合法的联系方式！'));
      }
      callback()
    };
    const checkEmail = (rule, value, callback) => {   //校验联系方式规则
      if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
        callback(new Error('请输入合法的邮箱地址！'));
      }
      callback()
    };
    return {
      form: {},
      rules: {
        username: [
          {required: true, message: '用户名不能为空', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '联系方式不能为空', trigger: 'blur'},
          {validator: checkPhone, trigger: 'blur'}
        ],
        email: [
          {required: true, message: '邮箱地址不能为空', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    const id = this.$route.query.id   //获取到查询参数id
    request.get("/admin/" + id).then(res => {
      if (res.code === '200') {
        this.form = res.data
      }
    })
  },
  methods: {
    save() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          request.put('/admin/update', this.form).then(res => {
            if (res.code === '200') {
              this.$notify.success('修改成功！')
              this.$router.push("/admin")   //跳转到列表界面
            } else {
              this.$notify.error('修改失败！' + res.msg)
            }
          })
        }
      })
    }
  }
}
</script>